<template>
  <!-- 背景   -->
  <div style="width: 100%; height: 100%; overflow: hidden; position: absolute; z-index: 1">
    <img style="width: 100%; height: 100%" src="./img/background.jpg" alt="" />
  </div>

  <div class="myform">
    <div style="margin: 20px auto; text-align: center">欢迎使用 顾家·统一登录平台</div>
    <!-- 登入表单   -->
    <div v-show="!switchAorP">
      <a-form :model="formState" name="basic" :wrapper-col="{ span: 24 }" autocomplete="off" @finish="onFinish">
        <a-form-item label="" name="username" :rules="[{ required: true, message: '请输入账号!' }]">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item label="" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">登录</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!--登录二维码-->
    <div v-show="switchAorP">
      <div style="margin: 20px; text-align: center"><span>请使用钉钉扫码登录</span></div>
      <div ref="refQrcode" style="width: 200px; height: 200px; margin: 10px auto"></div>
    </div>
    <div class="login-switch" @click="switchAorP = !switchAorP">
      {{ switchAorP ? '管理员登录' : '扫码登录' }}
    </div>
  </div>
</template>
<script setup>
import { useStoreLogin } from '@/pinia/login'
import { reactive, ref, onMounted } from 'vue'
import factory from './factory'
import QRCode from 'qrcodejs2'
import mqtt from 'mqtt'
import { message } from 'ant-design-vue'

/**获取cookie与MQTT参数,并生成二维码*/
const refQrcode = ref(null)
const cookie = ref(null)
onMounted(() => {
  getConfig()
})
// 获得二维码数据
async function getConfig() {
  let cookieConf = await factory.getUMCConfig()
  let arr = cookieConf.match(/{.*}/g)[0].split("'")
  let UMCConf = { posurl: arr[1], domain: arr[5], cookie: arr[1].split('/')[2] }
  cookie.value = UMCConf.cookie
  //mqtt参数获取
  let mqttConf = await factory.getMqttPrams(UMCConf.cookie)
  //生成二维码url获取
  let codeURL = [UMCConf.domain || location.origin, '/Auth?', UMCConf.cookie].join('')
  createQrcode(codeURL)
  mqttFun(mqttConf)
}
//mqtt连接与消息处理,websocket方式
function mqttFun(mqttConf) {
  //MQTT连接
  let options = {
    clean: true,
    connectTimeout: 30000,
    clientId: mqttConf.client,
    username: mqttConf.user,
    password: mqttConf.pass,
    keepalive: 60,
    protocol: 'mqtt',
  }
  const client = mqtt.connect('wss://' + mqttConf.broker, options)
  client.on('connect', () => {
    console.log('连接成功')
  })
  //失败重连
  client.on('reconnect', (error) => {
    console.log('正在重连:', error)
  })
  //连接失败
  client.on('error', (error) => {
    console.log('连接失败:', error)
  })
  //接收消息
  client.on('message', (topic, message) => {
    console.log('收到消息：', topic, message.toString())
    if (message.toString() === `[{"msg":"OK"}]`) {
      factory.scanQRcodeJump(cookie.value).then((res) => {
        if (res.ClientEvent === 64) {
          let useInfo = res.Headers.DataEvent
          useStoreLogin().login(useInfo, cookie.value)
        } else {
          let msg = res.Headers.Prompt.Text
          message.error(msg)
        }
      })
    }
  })
}
// QRCode插件生成二维码图片
function createQrcode(url) {
  let qrcode = new QRCode(refQrcode.value, {
    width: 200,
    height: 200,
  }).makeCode(url)
}

/**管理员登录与扫码登录切换*/
const switchAorP = ref(true)

/**账号密码登录*/
const formState = reactive({
  username: '',
  password: '',
  remember: true,
})
const onFinish = (log) => {
  factory.login(cookie.value, log.username, log.password).then((res) => {
    if (res.ClientEvent === 64) {
      let useInfo = res.Headers.DataEvent
      useStoreLogin().login(useInfo, cookie.value)
    } else {
      let msg = res.Headers.Prompt.Text
      message.error(msg)
    }
  })
}
</script>
<style scoped lang="less">
.myform {
  width: 329px;
  height: 417px;
  background-color: rgba(66, 72, 194, 0.2);
  position: relative;
  z-index: 2;
  top: 145px;
  left: 940px;
  padding: 20px 40px;
  box-sizing: border-box;
  .login-switch {
    bottom: 10px;
    margin-left: 10px;
    cursor: pointer;
  }
}
</style>
